<?php
namespace app\handler\wechat\ai;

use app\facade\Ai;
use EasyWeChat\Kernel\Contracts\EventHandlerInterface;
use EasyWeChat\Kernel\Messages\Text;

class VoiceMessageHandler implements EventHandlerInterface
{
    use BaseMessageHandler;

    public function handle($message = null)
    {
        $wechat = $this->getApp();
        $mediaId = $message['MediaId'] ?? '';
        $openid = $message['FromUserName'] ?? '';

        $stream = $wechat->media->get($mediaId);

        if ($stream && ! is_array($stream)) {

            //调AI 语音解释文本 临时素材取回的格式是amr 8000 rate jssdk是高清格式speex 16000 rate
            $res = Ai::aaiAsr([
                'speech' => base64_encode($stream->getBodyContents()),
                'format' => 3,
                'rate' => 8000
            ]);

            if ($res && is_array($res) && ! $res['ret']) {
                $text = trim($res['data']['text']);
                if ($text) {
                    $result = Ai::textTrans(['text' => $text, 'type' => 9]);
                    if ($result && is_array($result) && ! $result['ret']) {
                        $wechat->customer_service
                            ->message(new Text($result['data']['trans_text']))
                            ->to($openid)
                            ->send();
                        return;
                    }
                }
            }
        }
        $wechat->customer_service->message(new Text('您说啥？请再说一次'))->to($openid)->send();
    }
}
